package com.qny.ai.controller;

import com.qny.ai.common.ApiResponse;
import com.qny.ai.service.impl.AvatarUploadService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/api/avatar")
@RequiredArgsConstructor
public class AvatarController {

    private final AvatarUploadService avatarUploadService;

    /**
     * 生成单个角色头像
     */
    @PostMapping("/generate")
    public ApiResponse<String> generateAvatar(@RequestParam String roleName, @RequestParam String category) {
        log.info("生成头像请求 - 角色: {}, 类别: {}", roleName, category);
        
        String avatarUrl = avatarUploadService.generateAndUploadAvatar(roleName, category);
        
        if (avatarUrl != null) {
            log.info("头像生成成功: {}", avatarUrl);
            return ApiResponse.ok(avatarUrl);
        } else {
            log.error("头像生成失败");
            return ApiResponse.fail(500, "头像生成失败");
        }
    }

    /**
     * 批量生成系统角色头像
     */
    @GetMapping("/generate-system")
    public ApiResponse<String> generateSystemAvatars() {
        log.info("批量生成系统角色头像请求");
        
        try {
            avatarUploadService.generateSystemRoleAvatars();
            log.info("系统角色头像生成完成");
            return ApiResponse.ok("系统角色头像生成完成");
        } catch (Exception e) {
            log.error("批量生成头像失败: {}", e.getMessage());
            return ApiResponse.fail(500, "批量生成头像失败: " + e.getMessage());
        }
    }

    /**
     * 获取头像URL
     */
    @GetMapping("/url")
    public ApiResponse<String> getAvatarUrl(@RequestParam String roleName, @RequestParam String category) {
        String avatarUrl = avatarUploadService.getAvatarUrl(roleName, category);
        
        if (avatarUrl != null) {
            return ApiResponse.ok(avatarUrl);
        } else {
            return ApiResponse.fail(404, "头像不存在");
        }
    }

    /**
     * 清空头像缓存
     */
    @DeleteMapping("/cache")
    public ApiResponse<String> clearCache() {
        avatarUploadService.clearCache();
        return ApiResponse.ok("缓存已清空");
    }
}
